package com.labofjet.service;

import java.util.Arrays;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.labofjet.entity.Phone;
import com.labofjet.entity.Student;
import com.labofjet.repository.module1.ARepository;
import com.labofjet.repository.module2.PhoneRepository;
import com.labofjet.repository.module2.StudentRepository;

@Service
@Transactional
public class TestService {
    @Autowired
    private StudentRepository studentRepository;

    @Autowired
    private PhoneRepository phoneRepository;

    @Autowired
    private ARepository aRepository;

    public Student findById(long id) {
        return studentRepository.findOne(id);
    }

    public Student findByName(String name) {
        return studentRepository.findDistinctByName(name);
    }

    public List<Student> findStudentByPhonesPhoneName(String name) {
        return studentRepository.findStudentByPhonesPhoneName(name);
    }

    public List<Student> deleteStudentById(long id) {
        return studentRepository.deleteStudentById(id);
    }

    public Page<Student> findAll(Pageable pageable) {
        return studentRepository.findAll(pageable);
    }

    public List<Student> findByIds(List<Long> list) {
        return studentRepository.findByIdIn(list);
    }

    public List<Student> findTop2(Pageable pageable) {
        return studentRepository.findTop2By(pageable);
    }

    public List<Student> findTop3ByOrderByName(Pageable pageable) {
        return studentRepository.findTop3ByOrderByName(pageable);
    }

    public Student saveOne() {
        Student s = new Student();
        s.setName("NO.99");
        Phone p1 = new Phone();
        Phone p2 = new Phone();
        p1.setPhoneName("NO91");
        p2.setPhoneName("NO92");
        p2.setStudent(s);
        p1.setStudent(s);
        s.setPhones(Arrays.asList(p1, p2));
        return studentRepository.save(s);
    }

    public void updateOne(Student newStu) {
        studentRepository.save(newStu);
    }

    public Student saveOne(Student s) {
        return studentRepository.save(s);
    }
    
    public void testTransaction(){
        Phone phone = phoneRepository.findOne(1L);
        phone.setPhoneName("phone2");
    }
}
